package common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;


import net.sf.json.JSONObject;

public class WeatherUtil {
	public static Logger log = Logger.getLogger(WeatherUtil.class);
	/**
	 * 获取实时温度
	 * @param cityId
	 * @return
	 */
	public static Map<String,Object>  getWeatherInform(String cityId){  
	/*String baiduUrl =  "http://www.weather.com.cn/data/sk/"+cityId+".html";*/
		String baiduUrl ="http://wthrcdn.etouch.cn/weather_mini?citykey=101010100";
	StringBuffer strBuf = new StringBuffer(); 
	Map<String,Object> map = new HashMap<String,Object>();
	try{  
	    URL url = new URL(baiduUrl);  
	    URLConnection conn = url.openConnection();  
	    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//转码。  
	    String line = null;  
	    while ((line = reader.readLine()) != null)  
	    strBuf.append(line + " ");  
	    reader.close();  
	}catch(MalformedURLException e) {  
		log.error("WeatherUtil:getWeatherInform-->"+cityId+"Time:"+new Date());
	    e.printStackTrace();   
	}catch(IOException e){  
		log.error("WeatherUtil:getWeatherInform-->"+cityId+"Time:"+new Date());
	    e.printStackTrace();   
	}     
		JSONObject jsonData = JSONObject.fromObject(strBuf.toString());  
	    JSONObject info = jsonData.getJSONObject("weatherinfo");  
	    map.put("city", info.getString("city").toString());// 城市  
	    map.put("temp", info.getString("temp").toString());// 温度  
	    map.put("SD", info.getString("SD").toString());// 湿度  
	    map.put("time", info.getString("time").toString());// 发布时间  
	    return map;  
	}  

	public static void main(String[] args){
	WeatherUtil baidu = new WeatherUtil();
	System.out.println(baidu.getWeatherInform("101280601"));
	}
	
}